package cn.lili.modules.order.order.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.utils.StringUtils;
import cn.lili.modules.member.client.MemberEvaluationClient;
import cn.lili.modules.member.client.UnionClient;
import cn.lili.modules.member.entity.dos.Union;
import cn.lili.modules.member.entity.dto.MemberEvaluationDTO;
import cn.lili.modules.member.entity.enums.EvaluationGradeEnum;
import cn.lili.modules.operationcenter.client.OperationCenterClient;
import cn.lili.modules.operationcenter.entity.dos.OperationCenter;
import cn.lili.modules.order.aftersale.service.AfterSaleService;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.order.order.entity.dos.OrderFlow;
import cn.lili.modules.order.order.entity.dos.OrderItem;
import cn.lili.modules.order.order.entity.dto.OrderSearchParams;
import cn.lili.modules.order.order.entity.enums.CommentStatusEnum;
import cn.lili.modules.order.order.entity.enums.OrderComplaintStatusEnum;
import cn.lili.modules.order.order.entity.enums.OrderStatusEnum;
import cn.lili.modules.order.order.service.OrderFlowService;
import cn.lili.modules.order.order.service.OrderItemService;
import cn.lili.modules.order.order.service.OrderService;
import cn.lili.modules.system.client.SettingClient;
import cn.lili.modules.system.entity.dos.Setting;
import cn.lili.modules.system.entity.dto.OrderSetting;
import cn.lili.modules.system.entity.enums.SettingEnum;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单每日任务
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class OrderEveryDayTask {

    /**
     * 设置
     */
    private final SettingClient settingClient;
    /**
     * 会员评价
     */
    private final MemberEvaluationClient memberEvaluationClient;
    /**
     * 订单
     */
    private final OrderService orderService;
    /**
     * 订单流水
     */
    private final OrderFlowService orderFlowService;
    /**
     * 订单货物
     */
    private final OrderItemService orderItemService;

    /**
     * 售后业务
     */
    private final AfterSaleService afterSaleService;

    private final UnionClient unionClient;

    private final OperationCenterClient operationCenterClient;


    /**
     * 执行每日任务
     */
    public void execute() {

        Setting setting = settingClient.get(SettingEnum.ORDER_SETTING.name());
        //订单设置
        OrderSetting orderSetting = JSONUtil.toBean(setting.getSettingValue(), OrderSetting.class);
        if (orderSetting == null) {
            throw new ServiceException(ResultCode.ORDER_SETTING_ERROR);
        }

        //自动确认收货
        try {
            completedOrder(orderSetting);
        } catch (Exception e) {
            log.error("自动确认收货异常", e);
        }
        //自动好评
        try {
//            memberEvaluation(orderSetting);
        } catch (Exception e) {
            log.error("自动好评异常", e);
        }
        //关闭允许售后申请
        try {
            closeAfterSale(orderSetting);
        } catch (Exception e) {
            log.error("关闭允许售后申请异常", e);
        }
        //关闭允许投诉
        try {
            closeComplaint(orderSetting);
        } catch (Exception e) {
            log.error("关闭允许投诉异常", e);
        }

        try {
            //自动分账
            profitSharing();
        } catch (Exception e) {
            log.error("自动分账异常", e);
        }

    }

    /**
     * 自动分账
     */
    private void profitSharing() {
        //将待分账流水状态更新
        orderFlowService.updateProfitSharingStatus();
        //获取所有待分账的订单
        List<OrderFlow> orderFlows = orderFlowService.waitProfitSharingFlows();
        //订单挨个分账
        for (OrderFlow orderFlow : orderFlows) {
            try {
                Order order = orderService.getBySn(orderFlow.getOrderSn());
                if (null != order && StringUtils.isNotEmpty(order.getConsigneeAddressIdPath())) {
                    String[] address = order.getConsigneeAddressIdPath().split(",");
                    List<Union> unionList = unionClient.getListByFiled("city_id", address[1]);
                    if (!unionList.isEmpty()) {
                        orderFlow.setUnionId(unionList.get(0).getId());
                        OperationCenter operationCenter = operationCenterClient.getByAddressId(unionList.get(0).getProvinceId());
                        if (null != operationCenter) {
                            orderFlow.setOcUserId(operationCenter.getUserId());
                        }
                    }
                }
                orderFlowService.profitSharingOrderFlow(orderFlow);
            } catch (Exception e) {
                log.error("订单分账失败：{}", orderFlow.getSn(), e);
            }
        }
    }


    /**
     * 自动确认收获，订单完成
     *
     * @param orderSetting 订单设置
     */
    private void completedOrder(OrderSetting orderSetting) {
        //订单自动收货时间 = 当前时间 - 自动收货时间天数
        DateTime receiveTime = DateUtil.offsetDay(DateUtil.date(), -orderSetting.getAutoReceive());
        OrderSearchParams searchParams = new OrderSearchParams();
        searchParams.setOrderStatus(OrderStatusEnum.DELIVERED.name());
        //订单发货时间 >= 订单自动收货时间
        searchParams.setLeLogisticsTime(receiveTime);
        List<Order> list = orderService.queryListByParams(searchParams);
        for (Order order : list) {
            try {
                orderService.systemComplete(order.getSn());
            } catch (Exception e) {
                log.error("订单自动完成失败  {}：", order.getSn(), e);
            }
        }
    }

    /**
     * 自动好评
     *
     * @param orderSetting 订单设置
     */
    private void memberEvaluation(OrderSetting orderSetting) {
        //订单自动收货时间 = 当前时间 - 自动收货时间天数
        DateTime receiveTime = DateUtil.offsetDay(DateUtil.date(), -orderSetting.getAutoEvaluation());

        //订单完成时间 <= 订单自动好评时间
        OrderSearchParams searchParams = new OrderSearchParams();
        searchParams.setCommentStatus(CommentStatusEnum.UNFINISHED.name());
        searchParams.setLeCompleteTime(receiveTime);

        List<OrderItem> orderItems = orderItemService.waitOperationOrderItem(searchParams);

        //判断是否有符合条件的订单，进行自动评价处理
        if (!orderItems.isEmpty()) {
            for (OrderItem orderItem : orderItems) {
                try {
                    MemberEvaluationDTO memberEvaluationDTO = new MemberEvaluationDTO();
                    memberEvaluationDTO.setOrderItemSn(orderItem.getSn());
                    memberEvaluationDTO.setContent("系统默认好评");
                    memberEvaluationDTO.setGoodsId(orderItem.getGoodsId());
                    memberEvaluationDTO.setSkuId(orderItem.getSkuId());
                    memberEvaluationDTO.setGrade(EvaluationGradeEnum.GOOD.name());
                    memberEvaluationDTO.setDeliveryScore(5);
                    memberEvaluationDTO.setDescriptionScore(5);
                    memberEvaluationDTO.setServiceScore(5);

                    memberEvaluationClient.addMemberEvaluation(memberEvaluationDTO, false);
                } catch (Exception e) {
                    log.error("订单自动好评失败  {}：", orderItem.getSn(), e);
                }
            }
        }
    }


    /**
     * 关闭允许售后申请
     *
     * @param orderSetting 订单设置
     */
    private void closeAfterSale(OrderSetting orderSetting) {

        //订单关闭售后申请时间 = 当前时间 - 自动关闭售后申请天数
        DateTime expiredTime = DateUtil.offsetDay(DateUtil.date(), -orderSetting.getCloseAfterSale());

        //售后过期标识
        orderItemService.expiredAfterSaleStatus(expiredTime);
    }

    /**
     * 关闭允许交易投诉
     *
     * @param orderSetting 订单设置
     */
    private void closeComplaint(OrderSetting orderSetting) {

        //订单关闭交易投诉申请时间 = 当前时间 - 自动关闭交易投诉申请天数
        DateTime receiveTime = DateUtil.offsetDay(DateUtil.date(), -orderSetting.getCloseComplaint());

        //关闭售后订单=未售后订单+小于订单关闭售后申请时间
        OrderSearchParams searchParams = new OrderSearchParams();
        searchParams.setLeCompleteTime(receiveTime);
        searchParams.setComplainStatus(OrderComplaintStatusEnum.NO_APPLY.name());
        List<OrderItem> orderItems = orderItemService.waitOperationOrderItem(searchParams);

        //判断是否有符合条件的订单，关闭允许售后申请处理
        if (!orderItems.isEmpty()) {
            //获取订单货物ID
            List<String> orderItemIdList = orderItems.stream().map(OrderItem::getId).collect(Collectors.toList());
            //修改订单投诉状态
            orderItemService.updateComplainStatus(orderItemIdList);
        }

    }

}
